# -*- coding: utf-8 -*-
import os
import glob, sys
import datetime as dt
import pandas as pd
import numpy as np
import xarray as xr

# This script calculates the fraction of area that each fuel represents in a circle of radius d around the fire ignition point

d = int(sys.argv[1])

fuel_name = ['GR2', 'GR4', 'GR6', 'GR7', 'GR8',
             'GR9', 'SH2', 'SH3', 'SH5', 'SH7',
             'SH8', 'SH9', 'TU1', 'TU2', 'TU3',
             'TU5', 'TL3'] 

fires = pd.read_csv('../DATA/IberianPeninsula_fires_2001-2022.csv')
fires = fires[fires['Latitude']>35.].reset_index()

Fuels_fires=pd.DataFrame({})

path_fuel='../DATA/Fuel_map/'
ds_fuel = xr.open_dataset(path_fuel+'FBFM.nc').Band1
Distance = ds_fuel.copy()
lons, lats = np.meshgrid(ds_fuel.lon,ds_fuel.lat)
R = 6371.

for index in fires.index:

	data=fires['Data'][index]
	lon=fires['Longitude'][index]
	lat=fires['Latitude'][index]
	mun=fires['Municipio'][index]
	pro=fires['Provincia'][index]
	area=fires['Area'][index]


	Distance.values = np.sqrt((R*(lats-lat)*np.pi/180.)**2.+(R*np.cos(lat*np.pi/180.)*(lons-lon)*np.pi/180.)**2.)

	Fuels = ds_fuel.where((Distance<d) & (ds_fuel>0),drop=True)
	w_f = np.zeros(17)
	for f in range(1,18):
		w_f[f-1] = Fuels.where(Fuels==f).count()/Fuels.count()
	if np.sum(w_f)<0.99:
		print('ERRO en index: {}'.format(index))

	
	FF=pd.DataFrame({'Date':data,'Municipaliy':mun,'Province':pro,'Longitude':lon,'Latitude':lat,'Area':area,
			'GR2':float(w_f[0]),
			'GR4':float(w_f[1]),
			'GR6':float(w_f[2]),
			'GR7':float(w_f[3]),
			'GR8':float(w_f[4]),
			'GR9':float(w_f[5]),
			'SH2':float(w_f[6]),
			'SH3':float(w_f[7]),
			'SH5':float(w_f[8]),
			'SH7':float(w_f[9]),
			'SH8':float(w_f[10]),
			'SH9':float(w_f[11]),
			'TU1':float(w_f[12]),
			'TU2':float(w_f[13]),
			'TU3':float(w_f[14]),
			'TU5':float(w_f[15]),
			'TL3':float(w_f[16])
			},index={index})
	Fuels_fires=pd.concat([Fuels_fires,FF])

	print('{:.3f} %'.format(float(index/fires.index.size)*100.))

columns =  ['Longitude','Latitude','Area',
			'GR2', 'GR4', 'GR6', 'GR7', 'GR8',
			'GR9', 'SH2', 'SH3', 'SH5', 'SH7',
			'SH8', 'SH9', 'TU1', 'TU2', 'TU3',
			'TU5', 'TL3'] 

for column in columns:
	Fuels_fires[column] = Fuels_fires[column].astype('float32').map('{:.5f}'.format)
Fuels_fires.to_csv('../OUTS/Fuels_fires_d{}.csv'.format(str(int(d))))
